package com.example.blog.controller;

import com.example.blog.entity.User;
import com.example.blog.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.http.ResponseEntity;
import javax.validation.Valid;

@RestController
@RequestMapping("/api/users")
/* 修改时间：2024-04-21 16:20:00 */
public class UserController {

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResponseEntity<Map<String, String>> handleValidationExceptions(MethodArgumentNotValidException ex) {
        Map<String, String> errors = new HashMap<>();
        ex.getBindingResult().getFieldErrors().forEach(error -> {
            String fieldName = error.getField();
            String errorMessage = error.getDefaultMessage();
            errors.put(fieldName, errorMessage);
        });
        return ResponseEntity.badRequest().body(errors);
    }

    @Autowired
    private UserService userService;

    // 用户控制器类，处理用户相关的请求
    /* 修改时间：2024-04-21 16:20:00 */
    @PostMapping("/register")
    public ResponseEntity<String> register(@Valid @RequestBody User user) {
        userService.register(user);
        return ResponseEntity.ok("User registered successfully");
    }

    // 用户登录
    /* 修改时间：2024-04-21 16:20:00 */
    @PostMapping("/login")
    public Object login(@RequestBody User user) {
        System.out.println("收到登录请求，用户名：" + user.getUsername());
        
        // 先检查用户是否存在
        User existingUser = userService.findByUsername(user.getUsername());
        if (existingUser == null) {
            System.out.println("登录失败：用户名不存在 - " + user.getUsername());
            return "用户名不存在";
        }
        
        // 验证密码
        boolean isAuthenticated = userService.login(user);
        if (isAuthenticated) {
            System.out.println("登录成功：用户 - " + user.getUsername());
            // 创建包含用户信息和token的响应对象
            Map<String, Object> response = new HashMap<>();
            response.put("message", "Login successful");
            response.put("token", "user-token-" + existingUser.getId());
            response.put("user", existingUser);
            return response;
        } else {
            System.out.println("登录失败：密码错误 - 用户：" + user.getUsername());
            return "密码错误";
        }
    }
}